import React, { useState } from 'react';

import { InputNumber, InputNumberProps } from 'antd';
import { isNil, isNumber } from 'lodash-es';

const CustomizedInputNumber = ({
  value,
  diff = 0,
  precision,
  onBlur,
  onChange,
  ...props
}: InputNumberProps & { diff?: number; log?: boolean }): JSX.Element => {
  // 减去diff得到正确的值
  const currentValue = isNil(value) || diff === 0 ? value : +value - diff;

  // 当同时有精度和差值时，会有精度误差，需要进行精度展示处理
  const needHandlePrecision = isNumber(precision) && diff !== 0;
  const [showPrecision, setShowPrecision] = useState<number>(precision);

  const showValue =
    needHandlePrecision && isNumber(currentValue)
      ? +currentValue.toFixed(showPrecision)
      : currentValue;

  const handleBlur: React.FocusEventHandler<HTMLInputElement> = (e) => {
    onBlur?.(e);
    // 输入为空时，失焦需重置
    !isNumber(showValue) && onChange(0 + diff);
  };

  const handleChange = (newValue: InputNumberProps['value']): void => {
    if (needHandlePrecision && !isNil(newValue)) {
      // 输入的小数位和设置的精度可能不一致，这里需要修改展示精度
      const newPrecision = newValue.toString().split('.')[1]?.length || 0;
      setShowPrecision(newPrecision);
    }

    const currentNewValue =
      isNil(newValue) || diff === 0 ? newValue : +newValue + diff;
    onChange?.(currentNewValue);
  };

  return (
    <InputNumber
      {...props}
      value={showValue}
      precision={precision}
      onBlur={handleBlur}
      onChange={handleChange}
    />
  );
};

export default CustomizedInputNumber;
